export type AppConfig = {
  TUSHARE: {
    API_URL: string;
    API_TOKEN?: string;
    TIMEOUT_MS: number;
    MAX_REQUESTS_PER_MIN: number;
  };
  STORAGE: {
    ROOT: string; // base data dir
    ACTIVE_DIR: string; // hot data
    ARCHIVE_DIR: string; // cold data
    LOG_DIR: string;
  };
  JOBS: {
    DAILY_CRON: string; // cron expression for daily update
    TIMEZONE: string; // e.g., Asia/Shanghai
  };
};

function env(key: string, def?: string): string | undefined {
  const v = process.env[key];
  if (v === undefined || v === '') return def;
  return v;
}

export const CONFIG: AppConfig = {
  TUSHARE: {
    API_URL: env('TUSHARE_API_URL', 'https://api.tushare.pro')!,
    API_TOKEN: env('TUSHARE_TOKEN'),
    TIMEOUT_MS: Number(env('TUSHARE_TIMEOUT_MS', '20000')),
    MAX_REQUESTS_PER_MIN: Number(env('TUSHARE_RPM', '60')),
  },
  STORAGE: {
    ROOT: env('DATA_ROOT', 'data')!,
    ACTIVE_DIR: env('DATA_ACTIVE_DIR', 'data/active')!,
    ARCHIVE_DIR: env('DATA_ARCHIVE_DIR', 'data/archive')!,
    LOG_DIR: env('LOG_DIR', 'logs')!,
  },
  JOBS: {
    DAILY_CRON: env('DAILY_CRON', '0 0 * * *')!, // every day at 00:00
    TIMEZONE: env('TZ', 'Asia/Shanghai')!,
  },
};

export type RequestContext = {
  tushareToken?: string;
};

export function withContext<T>(ctx: RequestContext, fn: () => Promise<T>): Promise<T> {
  (global as any).__REQUEST_CONTEXT__ = ctx;
  return fn().finally(() => { (global as any).__REQUEST_CONTEXT__ = undefined; });
}

export function getContext(): RequestContext {
  const ctx = (global as any).__REQUEST_CONTEXT__ as RequestContext | undefined;
  return ctx || {};
}